<template>
  <div id="words" style="grid-row: 2/3; display: flex; row-gap: 20px; padding: 20px 200px; overflow-y: scroll; align-content: flex-start"
            :style="{flexDirection: isEdit ? 'row': 'column', columnGap: isEdit ? '20px': '0px', flexWrap: isEdit ? 'wrap' : 'nowrap'}">
    <div v-for="(word) of words" :key="word" style="background-color: pink; height: 120px; box-sizing: border-box; padding: 20px;
                border: 1px solid red;border-radius: 30px; display: flex; justify-content: center; align-items: center;position: relative"
                :style="{fontSize: isEdit ? '50px' : '50px'}">
      <div>{{word}}</div>
      <div class="remove" v-if="isEdit" style="position: absolute; top: 10px; right: 10px; font-size: 30px" @click="remove(word)">
        <i class="el-icon-error"></i>
      </div>
    </div>
    <div style="position: fixed; right: 20px; top: 20px">
      <el-button @click="edit()">{{isEdit ? '取消编辑' : '编辑'}}</el-button>
      <el-button @click="add()">添加</el-button>
    </div>
  </div>
</template>

<script>
import {selectCommonwordWords, updateCommonwordWords} from "@/api/controller.js"
import Sortable from 'sortablejs';
export default {
  name: "ViewCommonword",
  methods: {
    canSort() {
      this.sortable.option('disabled', false);
      this.sortable.option('sort', true)
    },
    notCanSort() {
      this.sortable.option('disabled', true);
      this.sortable.option('sort', false)
    },
    initSortable() {
      let wordsEl = document.getElementById('words');
      let self = this
      this.sortable = new Sortable(wordsEl, {
        sort: false,
        disabled: true,
        async onSort(event) {
          let removeItem = self.words.splice(event.oldIndex, 1)
          self.words.splice(event.newIndex, 0, removeItem[0])
          try {
            await updateCommonwordWords(self.words)
            await self.select()
          } catch(error) {
            this.$message({
              type: 'error',
              message: `常见字排序失败!`
            });
          }
        }
      });
    },
    async add() {
      try {
        let {value} = await this.$prompt('请输入新的常见字', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
        let isHas = this.words.includes(value)
        if (isHas) {
          this.$message({
            type: 'error',
            message: `常见字重复，添加失败!`
          });
          return
        }
        let newWords = [value, ...this.words]
        await updateCommonwordWords(newWords)
        await this.select()
      } catch(error) {
        console.log(error)
      }
    },
    edit() {
      this.isEdit = !this.isEdit
      if (this.isEdit) {
        this.canSort()
      } else {
        this.notCanSort()
      }
    },
    async select() {
      let result = await selectCommonwordWords()
      this.id = result.data[0].id
      this.words = JSON.parse(result.data[0].words)
    },
    async remove(word) {
      try {
        await this.$confirm('此操作将永久删除该常见字, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let words = this.words.filter(item => {
          return item !== word
        })
        try {
          await updateCommonwordWords(words)
          await this.select()
          this.$message({
            type: 'success',
            message: `常见字 ${word} 删除成功!`
          });
        } catch(error) {
          this.$message({
            type: 'error',
            message: `常见字 ${word} 删除失败!`
          });
        }
      } catch(error) {
        console.log(error)
      }
    }
  },
  data() {
    return {
      id: "",
      words: [],
      isEdit: false,
      sortable: null
    }
  },
  async mounted() {
    await this.select()
    this.initSortable()
  }
}
</script>

<style scoped>
.remove:hover {
  cursor: pointer;
  color: red;
}
</style>